package fr.cpe.j2ee.projet.ejb;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContextType;
import javax.persistence.Query;
import javax.persistence.TypedQuery;

public abstract class AbstractDAO<T>
{
	@PersistenceContext(unitName="PROJET-JPA")
	private EntityManager em;
	
	private String className;
	private Class<T> classType;
	
	public AbstractDAO(Class<T> type)
	{
		this.classType = type;
		this.className = type.getSimpleName();
	}
	
	protected TypedQuery<T> buildSelectQuery(String strQuery, List<Object> parameters)
	{
		int index = 1;
		TypedQuery<T> query = this.em.createQuery(strQuery, this.classType);
		
		for(Object param : parameters)
		{
			query.setParameter(index, param);
			index++;
		}
		
		return query;
	}
	
	protected boolean exists(List<Object> criterias)
	{
		int index = 1;
		Query query = this.em.createNamedQuery(this.className + ".exists", this.classType);
		
		for(Object crit : criterias)
		{
			query.setParameter(index, crit);
			index++;
		}
		
		return query.getResultList().size() >= 1;
	}
	
	public List<T> getAll()
	{
		TypedQuery<T> query = this.em.createNamedQuery(this.className + ".findAll", this.classType);
		return query.getResultList();
	}
	
	public T getById(int id)
	{
		return this.em.find(this.classType, id);
	}
	
	public void insert(T entity)
	{
		this.em.persist(entity);
	}

	public void remove(T entity)
	{
		this.em.remove(entity);
	}
	
	public T update(T entity)
	{
		return this.em.merge(entity);
	}	
}
